package com.xbts.system.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.annotation.OrderBy;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xbts.common.core.domain.entity.SysDept;
import com.xbts.common.exception.ServiceException;
import com.xbts.common.utils.StringUtils;
import com.xbts.system.domain.CnSolution;
import com.xbts.system.mapper.CnSolutionMapper;
import com.xbts.system.service.ICnSolutionService;
import org.springframework.stereotype.Service;
import com.xbts.common.utils.SecurityUtils;

/**
 * 解决方案Solution业务层处理
 *
 * @author xbts
 * @date 2023-08-07
 */
@Service
public class CnSolutionServiceImpl extends ServiceImpl<CnSolutionMapper, CnSolution> implements ICnSolutionService {
    /**
     * 查询Solution
     *
     * @return Solution表
     */
    @Override
    public List<CnSolution> selectCnSolution() {
//        QueryWrapper<CnSolution> queryWrapper = new QueryWrapper<>();
//        queryWrapper.orderByAsc("sort", "parent_id");
//        List<CnSolution> table = list(queryWrapper);
        List<CnSolution> table = baseMapper.getList();
        return getTree(table);
    }

    private List<CnSolution> getTree(List<CnSolution> table) {
        Map<String, CnSolution> map = table.stream().collect(Collectors.toMap(CnSolution::getSolutionId, v -> v, (v1, v2) -> v1));
        List<CnSolution> rootNode = table.stream().filter(c -> c.getParentId().equals("0")).collect(Collectors.toList());
        for (CnSolution cnSolution : table) {
            String parentId = cnSolution.getParentId();
            if (!parentId.equals("0")) {
                if (map.get(parentId).getChildren() == null) {
                    map.get(parentId).setChildren(new ArrayList<>());
                    int length = cnSolution.getAncestors().split(",").length;
                    // 将最后一级的内容放到上级
                    if (length == 2){
                        map.get(parentId).setContent(cnSolution.getContent());
                        continue;
                    }
                }
                map.get(parentId).getChildren().add(cnSolution);
            }
        }
        return rootNode;
    }

    /**
     * 新增解决方案
     *
     * @param cnSolution 解决方案
     * @return 结果
     */
    @Override
    public boolean insertCnSolution(CnSolution cnSolution) {
        QueryWrapper<CnSolution> queryWrapper = new QueryWrapper<>();
        // 如果排序为空，则设置默认值
        if (null == cnSolution.getSort()){
            queryWrapper.select("(ifnull(max(sort), 0) + 1) as sort").eq("parent_id", cnSolution.getParentId());
            Integer nextSort = getOne(queryWrapper).getSort();
            cnSolution.setSort(nextSort);
        }
        cnSolution.setCreateBy(SecurityUtils.getUserId().toString());
        if (cnSolution.getParentId().equals("0")){
            cnSolution.setAncestors("0");
        } else {
            CnSolution dbCnSolution = getById(cnSolution.getParentId());
            cnSolution.setAncestors(dbCnSolution.getAncestors() + "," + cnSolution.getParentId());
        }

        return save(cnSolution);
    }

    /**
     * 删除
     *
     * @param SolutionId 主键id
     * @return 结果
     */
    public boolean deleteContentById(Long SolutionId) {
        long count = this.count(new LambdaQueryWrapper<CnSolution>()
                .eq(CnSolution::getParentId, SolutionId));
        if(count > 0){
            throw new ServiceException("存在子级，不能删除！");
        }
        return removeById(SolutionId);
    }

    /**
     * 批量删除Solution解决方法
     *
     * @param ids 多个主键id
     * @return 结果
     */
    public boolean batchDeleteContentById(List<Long> ids) {
        long count = this.count(new LambdaQueryWrapper<CnSolution>()
                .in(CnSolution::getParentId, ids));
        if(count > 0){
            throw new ServiceException("存在子级，不能删除！");
        }
        return removeBatchByIds(ids);
    }

    /**
     * 更新解决方法
     *
     * @param cnSolution 解决方案
     * @return 结果
     */
    public boolean updateSolution(CnSolution cnSolution) {
        QueryWrapper<CnSolution> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("solution_id", cnSolution.getSolutionId());
        return update(cnSolution, queryWrapper);
    }

    @Override
    public List<CnSolution> selectCnSolutionByParentId(String parentId) {
        LambdaQueryWrapper<CnSolution> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CnSolution::getParentId, parentId);
        queryWrapper.orderByAsc(CnSolution::getSort);
        return list(queryWrapper);
    }

    @Override
    public List<CnSolution> getTypeList() {
        List<CnSolution> table = baseMapper.getTypeList();
        Map<String, CnSolution> map = table.stream().collect(Collectors.toMap(CnSolution::getSolutionId, v -> v));

        List<CnSolution> result = new ArrayList<>();

        for (CnSolution cnSolution : table) {

            if(StringUtils.isBlank(cnSolution.getParentId()) || cnSolution.getParentId().equals("0")){
                result.add(cnSolution);
            } else {
                CnSolution solution = map.get(cnSolution.getParentId());
                if(StringUtils.isNotNull(solution)){
                    solution.getChildren().add(cnSolution);
                }
            }
        }
        return result;
    }
}